package zhixin.Utils;

import com.alibaba.fastjson.JSON;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;

import java.io.*;
import java.util.List;
import java.util.Set;

/**
 * @program: demo01
 * @description:
 * @author: 致心
 * @create: 2020-08-28 14:10
 **/
public class Cookies {

    public static void getC(WebDriver dr, String url) throws IOException, InterruptedException {
        File file = new File("TestCookies.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        StringBuilder cookiesJsonString = new StringBuilder();
        br.lines().forEach(cookiesJsonString::append);
        List<Cookie> cookies = JSON.parseArray(cookiesJsonString.toString().trim(), Cookie.class);
        if (cookies != null && cookies.size() > 0) {
            dr.manage().deleteAllCookies();
            cookies.forEach(res->{
                dr.manage().addCookie(new Cookie(
                        res.getName(),
                        res.getValue(),
                        res.getDomain(),
                        res.getPath(),
                        res.getExpiry(),
                        res.isSecure(),
                        res.isHttpOnly()
                ));
            });
            dr.get(url);
        }
    }

    public static void wtriteC(WebDriver dr) {
        File file = new File("TestCookies.txt");
        Set<Cookie> s = dr.manage().getCookies();
        if (file.exists()) {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            String cookiesJsonString = JSON.toJSONString(s);
            bw.write(cookiesJsonString);
            bw.flush();
            bw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
